<template>
	<div class="app-container">
		<el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="72px" class="queryForms">
			<el-form-item label="任务单号" prop="repairNumber">
				<el-input v-model="queryParams.repairNumber" placeholder="请输入任务单号" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="状态" prop="malfunctionStatus">
				<el-select v-model="queryParams.malfunctionStatus" placeholder="请选择">
					<el-option v-for="dict in dict.type.fault_status" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
				</el-select>
			</el-form-item>
			<el-form-item label="产品名称" prop="productName">
				<el-input v-model="queryParams.productName" placeholder="请输入产品名称" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="产品型号" prop="productModel">
				<el-input v-model="queryParams.productModel" placeholder="请输入产品型号" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="产品编号" prop="productNumber">
				<el-input v-model="queryParams.productNumber" placeholder="请输入产品编号" clearable @keyup.enter.native="handleQuery" maxlength="20" show-word-limit />
			</el-form-item>
			<el-form-item label="故障核实审批状态" prop="malfunctionApprovalStatus" label-width="140px">
				<el-select v-model="queryParams.malfunctionApprovalStatus">
					<el-option v-for="item in ApprovalStatusList" :key="item.id" :label="item.name" :value="item.id"> </el-option>
				</el-select>
			</el-form-item>
			<el-form-item>
				<el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
				<el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
			</el-form-item>
		</el-form>

		<el-row :gutter="10" class="mb8">
			<el-col :span="1.5">
				<el-button type="primary" size="mini" @click="handleUpload" v-hasPermi="['fault:faultlist:upload']">上传工艺通知</el-button>
			</el-col>
			<!-- <el-col :span="1.5">
				<el-button type="primary" size="mini" @click="handleSubmits" v-hasPermi="['fault:faultlist:submit']">提交</el-button>
			</el-col> -->
			<el-col :span="1.5">
				<el-button type="primary" size="mini" @click="handleApprove({})" v-hasPermi="['fault:faultlist:approve']">审批</el-button>
			</el-col>
			<el-col :span="1.5">
				<el-button size="mini" type="" @click="handleEditMore" v-hasPermi="['fault:faultlist:handle']">故障核实</el-button>
			</el-col>
			<CreateForm :ids="ids" formtype="t_repair_product" />
			<right-toolbar @changeTableData="changeTableData" menuNames="faultlist15" :showSearch.sync="showSearch" @queryTable="handleQuery" :columns.sync="columns" perm="fault:faultlist:index"></right-toolbar>
		</el-row>
		<div :class="sidebar.opened && eleTabTop <= 85 ? 'eleTab' : !sidebar.opened && eleTabTop <= 85 ? 'eleTabs' : ''" class="informationTab" ref="eleTab">
			<el-table
				:key="treetablekey"
				@expand-change="handleExpandChange"
				:default-expand-all="false"
				@mousedown.native="mousedownTable"
				@row-click="row_click"
				@cell-mouse-enter="cell_mouse_enter"
				@cell-mouse-leave="cell_mouse_leave"
				@mouseup.native="mouseupTable"
				@mouseleave.native="mouseupTable"
				ref="table"
				v-loading="loading"
				:data="FaultList"
				@selection-change="handleSelectionChange"
				row-key="id"
				lazy
				:load="loadListDes"
				:tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
				border
				height="100%">
				<el-table-column type="selection" width="55" align="center" />
				<el-table-column label="序号" align="center" type="index" width="55">
					           <template slot-scope="scope">
						<div>{{ scope.row.sort }}</div>
					</template>
				</el-table-column>
				<el-table-column label="返修任务单" prop="repairNumber" min-width="250" :show-overflow-tooltip="true" v-if="columns[0].visible" />
				<el-table-column label="客户代表" prop="productRepresentativeName" min-width="150" :show-overflow-tooltip="true" v-if="columns[1].visible" />
				<el-table-column label="用户" prop="clientName" min-width="150" :show-overflow-tooltip="true" v-if="columns[2].visible" />
				<el-table-column label="产品名称" prop="productName" min-width="150" :show-overflow-tooltip="true" v-if="columns[3].visible" />
				<el-table-column label="产品型号" prop="productModel" min-width="150" :show-overflow-tooltip="true" v-if="columns[4].visible" />
				<el-table-column label="产品编号" prop="productNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[5].visible" />
				<el-table-column label="产品数量" align="center" prop="productQuantity" min-width="150" :show-overflow-tooltip="true" v-if="columns[6].visible" />
				<el-table-column label="核实故障日期" align="center" prop="malfunctionVerifyTime" min-width="150" :show-overflow-tooltip="true" v-if="columns[7].visible" />
				<el-table-column label="维修类别" prop="maintenanceCategoryName" min-width="150" :show-overflow-tooltip="true" v-if="columns[8].visible" />
				<!-- 故障原因不显示 -->
				<!-- <el-table-column label="故障原因" prop="deviceTypeName" min-width="150" :show-overflow-tooltip="true" /> -->
				<el-table-column label="故障模式" prop="failureMode" min-width="150" :show-overflow-tooltip="true" v-if="columns[9].visible" />
				<el-table-column label="故障核实情况" prop="failureRemark" min-width="150" :show-overflow-tooltip="true" v-if="columns[10].visible" />
				<el-table-column label="状态" prop="malfunctionStatus" min-width="150" :show-overflow-tooltip="true" align="center" v-if="columns[11].visible">
					<template slot-scope="scope">
						<div v-if="scope.row.hasChildren">
							<div v-if="scope.row.repairMalfunctionStatus === '0'" style="color: #666">待核实</div>
							<div v-if="scope.row.repairMalfunctionStatus === '1'" style="color: #e1756d">待提交</div>
							<div v-if="scope.row.repairMalfunctionStatus === '2'" style="color: #63b0b3">进行中</div>
							<div v-if="scope.row.repairMalfunctionStatus === '3'" style="color: #7ebf27">已完成</div>
						</div>
						<div v-else>
							<el-tag v-if="scope.row.malfunctionStatus === '0'" style="color: #666">
								<dict-tag :options="dict.type.fault_status" :value="scope.row.malfunctionStatus" />
							</el-tag>
							<el-tag v-if="scope.row.malfunctionStatus === '1'" style="color: #e1756d">
								<dict-tag :options="dict.type.fault_status" :value="scope.row.malfunctionStatus" />
							</el-tag>
							<el-tag v-if="scope.row.malfunctionStatus === '2'" style="color: #63b0b3">
								<dict-tag :options="dict.type.fault_status" :value="scope.row.malfunctionStatus" />
							</el-tag>
							<el-tag v-if="scope.row.malfunctionStatus === '3'" style="color: #7ebf27">
								<dict-tag :options="dict.type.fault_status" :value="scope.row.malfunctionStatus" />
							</el-tag>
						</div>
					</template>
				</el-table-column>
				<el-table-column align="center" label="工艺通知单编号" prop="processNumber" min-width="150" :show-overflow-tooltip="true" v-if="columns[12].visible">
					<template slot-scope="scope">
						<div v-if="scope.row.hasChildren">
							<div v-if="scope.row.processNumber == 1" style="color: red">未上传</div>
							<div v-if="scope.row.processNumber == 2" style="color: orange">部分上传</div>
							<div v-if="scope.row.processNumber == 3" style="color: green">全部上传</div>
							<!-- {{ scope.row.processNumber == 1 ? "未上传" : scope.row.processNumber == 2 ? "部分上传" : "全部上传" }} -->
						</div>
						<div v-else>
							{{ scope.row.processNumber }}
						</div>
					</template>
				</el-table-column>
				<el-table-column label="审批状态" prop="malfunctionApprovalStatus" min-width="150" align="center" :show-overflow-tooltip="true" v-if="columns[13].visible">
					<template slot-scope="scope">
						<div v-if="scope.row.hasChildren">
							<div v-if="scope.row.malfunctionApprovalStatus == 1" style="color: red">需审批</div>
							<div v-if="scope.row.malfunctionApprovalStatus == 2" style="color: green">已完成</div>
							<!-- <el-tag type="warning" v-if="scope.row.malfunctionApprovalStatus == 1"> 需审批 </el-tag>
							<el-tag type="success" v-if="scope.row.malfunctionApprovalStatus == 2"> 已完成 </el-tag> -->
						</div>
						<div v-else>
							<el-tag type="info" v-if="scope.row.malfunctionApprovalStatus === '0'" class="disableClick">
								<dict-tag :options="dict.type.default_approve" :value="scope.row.malfunctionApprovalStatus" />
							</el-tag>
							<el-tag v-if="scope.row.malfunctionApprovalStatus === '1'" @click="showApproveList(scope.row)" class="clickable">
								<dict-tag :options="dict.type.default_approve" :value="scope.row.malfunctionApprovalStatus" />
							</el-tag>
							<el-tag type="success" v-if="scope.row.malfunctionApprovalStatus === '2'" @click="showApproveList(scope.row)" class="clickable">
								<dict-tag :options="dict.type.default_approve" :value="scope.row.malfunctionApprovalStatus" />
							</el-tag>
							<el-tag type="danger" v-if="scope.row.malfunctionApprovalStatus === '3'" @click="showApproveList(scope.row)" class="clickable">
								<dict-tag :options="dict.type.default_approve" :value="scope.row.malfunctionApprovalStatus" />
							</el-tag>
						</div>
					</template>
				</el-table-column>
				<el-table-column label="核查单上传" align="center" prop="malfunctionFileFlag" min-width="150" :show-overflow-tooltip="true" v-if="columns[14].visible">
					<template slot-scope="scope">
						<div v-if="scope.row.malfunctionFileFlag == 0"></div>
						<div v-if="scope.row.malfunctionFileFlag == 1">已上传</div>
					</template>
				</el-table-column>
				<el-table-column label="退修状态" align="center" prop="retirementRepairlStatus" min-width="150" :show-overflow-tooltip="true" v-if="columns[15].visible">
					<template slot-scope="scope">
						<el-tag type="success" v-if="scope.row.retirementRepairlStatus == 1">已退修</el-tag>
						<div v-if="scope.row.retirementRepairlStatus == 0"></div>
					</template>
				</el-table-column>
				<el-table-column label="退修原因" prop="retirementRepairReason" min-width="150" :show-overflow-tooltip="true" v-if="columns[16].visible" />
				<el-table-column label="操作" class-name="small-padding fixed-width" width="320px" fixed="right">
					<template slot-scope="scope">
						<section v-if="scope.row.hasChildren">
							<el-button size="mini" type="text" icon="el-icon-view" @click="handleIng(scope.row)" v-hasPermi="['fault:faultlist:detailrecords']">零组件检查</el-button>
							<el-button size="mini" type="text" icon="el-icon-edit" @click="handleDetail(scope.row)" v-hasPermi="['fault:faultlist:detail']">详情</el-button>
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex(scope.row)" v-hasPermi="['fault:faultlist:annex']">附件</el-button>
						</section>
						<section v-else>
							<el-button size="mini" type="text" icon="el-icon-edit" @click="handleEdit(scope.row)" v-if="scope.row.malfunctionApprovalStatus == '0' || scope.row.malfunctionApprovalStatus == '3'" v-hasPermi="['fault:faultlist:handle']">故障核实</el-button>
							<!-- <el-button size="mini" type="text" icon="el-icon-circle-check" @click="handleSubmit(scope.row)" v-if="(scope.row.malfunctionApprovalStatus == '0' && scope.row.malfunctionStatus != '2') || (scope.row.malfunctionApprovalStatus == '3' && scope.row.malfunctionStatus != '2')" v-hasPermi="['fault:faultlist:submit']">提交</el-button> -->
							<!-- 审批中显示 -->
							<el-button size="mini" type="text" icon="el-icon-edit" @click="handleApprove(scope.row)" v-if="scope.row.existApprovalStatus == '0' && scope.row.malfunctionApprovalStatus != '2' && scope.row.malfunctionApprovalStatus != '3'" v-hasPermi="['fault:faultlist:approve']">审批</el-button>
							<el-button size="mini" type="text" icon="el-icon-edit" @click="handlebacks(scope.row)" v-if="!scope.row.hasChildren && scope.row.retirementRepairlStatus == 0" v-hasPermi="['erp:repair:repaqirBack']">退修</el-button>
							<el-button size="mini" type="text" icon="el-icon-edit" @click="handleDetailChild(scope.row)" v-hasPermi="['fault:faultlist:detail2']">详情</el-button>
							<el-button size="mini" type="text" icon="el-icon-wallet" @click="handleAnnex2(scope.row)" v-hasPermi="['fault:faultlist:annex2']">附件</el-button>
						</section>
					</template>
				</el-table-column>
			</el-table>
		</div>

		<pagination menuNames="Pagination17" v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

		<!-- 故障核实对话框 -->
		<el-dialog :title="title" :visible.sync="open" width="900px" append-to-body v-dialogDrag>
			<el-form ref="form" :model="form" :rules="rules" label-width="120px" class="add-form2" :disabled="disabled">
				<div class="form-title">
					<span class="title-msg">基本信息</span>
				</div>
				<el-form-item label="返修任务单号" prop="repairNumber" v-show="form.id !== 0">
					<el-input v-model="form.repairNumber" disabled />
				</el-form-item>
				<el-form-item label="产品名称" prop="productName" v-show="form.id !== 0">
					<el-input v-model="form.productName" disabled />
				</el-form-item>
				<el-form-item label="产品型号" prop="productModel" v-show="form.id !== 0">
					<el-input v-model="form.productModel" disabled />
				</el-form-item>
				<el-form-item label="产品编号" prop="productNumber" v-show="form.id !== 0">
					<el-input v-model="form.productNumber" disabled />
				</el-form-item>
				<el-form-item label="产品接收日期" prop="receiptTime" v-show="form.id !== 0">
					<el-input v-model="form.receiptTime" disabled />
				</el-form-item>
				<div v-show="form.id !== 0"></div>
				<el-form-item label="故障核实日期" prop="malfunctionVerifyTime">
					<el-date-picker v-model="form.malfunctionVerifyTime" type="date" value-format="yyyy-MM-dd" placeholder="请选择"> </el-date-picker>
				</el-form-item>
				<el-form-item label="维修类别" prop="maintenanceCategoryId">
					<el-select v-model="form.maintenanceCategoryId" placeholder="请选择" @change="changeCat">
						<el-option v-for="dict in dict.type.maintain_cat" :key="dict.value" :label="dict.label" :value="dict.value"> </el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="故障模式" prop="failureMode" style="width: 100%">
					<el-input v-model="form.failureMode" type="textarea" disabled />
				</el-form-item>
				<div class="form-title">
					<span class="title-msg">核实情况</span>
				</div>
				<el-form-item label="状态" prop="malfunctionStatus" style="width: 100%">
					<el-radio v-model="form.malfunctionStatus" label="0">核实无故</el-radio>
					<el-radio v-model="form.malfunctionStatus" label="1">核实有故</el-radio>
					<el-radio v-model="form.malfunctionStatus" label="3">正常</el-radio>
				</el-form-item>
				<el-form-item label="核实情况" prop="failureRemark" style="width: 100%">
					<el-input v-model="form.failureRemark" placeholder="核实情况说明" type="textarea" />
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitForm">确 定</el-button>
				<el-button @click="cancel">取 消</el-button>
			</div>
		</el-dialog>

		<el-dialog title="返修任务详情" :visible.sync="openDetail" width="900px" append-to-body v-dialogDrag>
			<RepairInfo ref="repairdetail" />
		</el-dialog>
		<el-dialog title="上传工艺通知单" :visible.sync="uploadOpen" width="900px" append-to-body v-dialogDrag>
			<el-form ref="uploadform" :model="uploadForm" :rules="uploadRules" label-width="140px" class="add-form1">
				<el-form-item label="工艺通知单编号" prop="processNumber">
					<el-input v-model="uploadForm.processNumber" placeholder="请输入工艺通知单编号" maxlength="20" show-word-limit />
				</el-form-item>
				<el-form-item label="工艺通知单">
					<FileUpload @input="getFiles" :value="uploadList" :limit="1"></FileUpload>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitFormUpload">确 定</el-button>
				<el-button @click="cancelUpload">取 消</el-button>
			</div>
		</el-dialog>
		<!-- 审批弹框 -->
		<el-dialog title="审批" :visible.sync="openApprove" width="900px" append-to-body v-dialogDrag>
			<ApproveTemplete @cancelApprove="cancelApprove" :openApprove="openApprove"></ApproveTemplete>
		</el-dialog>
		<!-- 审批流程弹框 -->
		<el-dialog title="审批流程" :visible.sync="openRecords" width="900px" append-to-body v-dialogDrag>
			<RecordsTemplete :approveRecord="approveRecord"></RecordsTemplete>
		</el-dialog>

		<el-dialog title="零组件检查记录" :visible.sync="partRecords" width="900px" append-to-body v-dialogDrag>
			<div style="height: 70vh; overflow-y: auto; padding-right: 15px">
				<!-- <div v-for="(item, index) in productRecords" :key="index"> -->
				<el-table :data="productRecords" style="margin-bottom: 20px">
					<el-table-column label="序号" width="55" type="index" />
					<el-table-column label="产品图号" prop="productModel" min-width="150" show-overflow-tooltip=""> </el-table-column>
					<el-table-column label="产品名称" prop="productName" min-width="120" show-overflow-tooltip=""> </el-table-column>
					<el-table-column label="检验依据" prop="processNumber" min-width="150" show-overflow-tooltip=""> </el-table-column>
					<el-table-column label="数量" prop="quantity" min-width="150" show-overflow-tooltip="" align="center"> </el-table-column>
					<el-table-column label="操作" class-name="small-padding fixed-width" width="200px" fixed="right" align="center">
						<template slot-scope="scope">
							<el-button size="mini" type="text" icon="el-icon-view" @click="detailsRecords(scope.row)">详情</el-button>
							<el-button size="mini" type="text" icon="el-icon-download" @click="detailsDownload(scope.row)">下载表单</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</el-dialog>

		<el-dialog title="修改零组件检查记录" :visible.sync="editRecords" width="900px" append-to-body v-dialogDrag>
			<div style="height: 70vh; overflow-y: auto; padding-right: 15px">
				<el-form :model="editRowForm" size="small" :inline="true" label-width="100px">
					<el-form-item label="产品图号" prop="productModel">
						<el-input v-model="editRowForm.productModel" placeholder="请输入产品图号" disabled />
					</el-form-item>
					<el-form-item label="产品名称" prop="productName">
						<el-input v-model="editRowForm.productName" placeholder="请输入产品名称" disabled />
					</el-form-item>
					<el-form-item label="检验依据" prop="processNumber">
						<el-input v-model="editRowForm.processNumber" placeholder="请输入检验依据" disabled />
					</el-form-item>
					<el-form-item label="数量" prop="quantity">
						<el-input v-model="editRowForm.quantity" placeholder="请输入数量" disabled />
					</el-form-item>
					<el-form-item label="记录时间" prop="recordTime">
						<el-date-picker format="yyyy-MM-dd" value-format="yyyy-MM-dd" v-model="editRowForm.recordTime" type="date" placeholder="选择日期"> </el-date-picker>
					</el-form-item>
				</el-form>
				<!-- <div v-for="(item, index) in detailsRecords" :key="index"> -->
				<el-table :data="detailsRecordsList" style="margin-bottom: 20px">
					<el-table-column label="序号" width="55" type="index" />
					<el-table-column label="检验内容" prop="programTests" min-width="150" show-overflow-tooltip="" align="center">
						<template slot-scope="scope">
							<el-input v-model="scope.row.programTests" maxlength="200"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="结论" prop="conclusion" min-width="120" show-overflow-tooltip="" align="center">
						<template slot-scope="scope">
							<el-input v-model="scope.row.conclusion" maxlength="200"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="检验员" prop="recipientId" min-width="100" show-overflow-tooltip="" align="center">
						<template slot-scope="scope">
							<el-select v-model="scope.row.recipientId" @change="selectusers($event, scope.row)">
								<el-option v-for="item in allocatedListData" :key="item.userId" :value="item.userId" :label="item.nickName"></el-option>
							</el-select>
						</template>
					</el-table-column>

					<el-table-column label="备注" prop="remark" min-width="150" show-overflow-tooltip="" align="center">
						<template slot-scope="scope">
							<el-input v-model="scope.row.remark" maxlength="100"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="操作" class-name="small-padding fixed-width" width="200px" fixed="right" align="center">
						<template slot-scope="scope">
							<el-button size="mini" type="text" icon="el-icon-plus" @click="addRecords(scope.row)">添加</el-button>
							<el-button size="mini" type="text" icon="el-icon-delete" @click="deleteRecords(scope.$index, scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
				<!-- </div> -->
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitFormRecords">确 定</el-button>
				<el-button @click="editRecords = false">取 消</el-button>
			</div>
		</el-dialog>

		<el-dialog title="多余物记录列表" :visible.sync="componentOpen" width="900px" append-to-body v-dialogDrag>
			<div style="height: 70vh; overflow-y: auto; padding-right: 15px">
				<el-table :data="compentRecords" style="margin-bottom: 20px">
					<el-table-column label="序号" width="55" type="index" />
					<el-table-column label="产品图号" prop="productModel" min-width="150" show-overflow-tooltip=""> </el-table-column>
					<el-table-column label="产品名称" prop="productName" min-width="120" show-overflow-tooltip=""> </el-table-column>
					<el-table-column label="数量" prop="quantity" min-width="150" show-overflow-tooltip="" align="center"> </el-table-column>
					<el-table-column label="操作" class-name="small-padding fixed-width" width="200px" fixed="right" align="center">
						<template slot-scope="scope">
							<el-button size="mini" type="text" icon="el-icon-view" @click="detailsComponents(scope.row)">详情</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
		</el-dialog>

		<el-dialog title="修改零组件检查记录" :visible.sync="editconponents" width="90%" append-to-body v-dialogDrag>
			<div style="height: 70vh; overflow-y: auto; padding-right: 15px">
				<el-table :data="detailscomponentsList" style="margin-bottom: 20px" @row-click="handleRowClick">
					<el-table-column label="工序号" prop="processNumber" min-width="170" align="center">
						<template slot-scope="scope">
							<el-input-number v-model="scope.row.processNumber" :min="1" :max="10000000" style="width: 150px"></el-input-number>
						</template>
					</el-table-column>
					<el-table-column label="工序名称" prop="processName" min-width="150" show-overflow-tooltip="" align="center">
						<template slot-scope="scope">
							<el-input v-model="scope.row.processName" maxlength="200"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="检查结果" prop="conclusion" min-width="120" show-overflow-tooltip="" align="center">
						<template slot-scope="scope">
							<el-input v-model="scope.row.conclusion" maxlength="200"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="工人" prop="workerId" min-width="120" show-overflow-tooltip="" align="center">
						<template slot-scope="scope">
							<el-select v-model="scope.row.workerId" @change="selectComponentusers($event, scope.row)">
								<el-option v-for="item in worksData" :key="item.userId" :value="item.userId" :label="item.nickName"></el-option>
							</el-select>
						</template>
					</el-table-column>
					<el-table-column label="工人时间" prop="workerTime" min-width="180" show-overflow-tooltip="" align="center">
						<template slot-scope="scope">
							<el-date-picker style="width: 150px" v-model="scope.row.workerTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"> </el-date-picker>
						</template>
					</el-table-column>
					<el-table-column label="检验人" prop="recipientId" min-width="120" show-overflow-tooltip="" align="center">
						<template slot-scope="scope">
							<el-select v-model="scope.row.recipientId" @change="selectComponentrecipient($event, scope.row)">
								<el-option v-for="item in usersData" :key="item.userId" :value="item.userId" :label="item.nickName"></el-option>
							</el-select>
						</template>
					</el-table-column>
					<el-table-column label="检验时间" prop="recipientTime" min-width="180" show-overflow-tooltip="" align="center">
						<template slot-scope="scope">
							<el-date-picker style="width: 150px" v-model="scope.row.recipientTime" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"> </el-date-picker>
						</template>
					</el-table-column>
					<el-table-column label="备注" prop="remark" min-width="150" show-overflow-tooltip="" align="center">
						<template slot-scope="scope">
							<el-input v-model="scope.row.remark" maxlength="100"></el-input>
						</template>
					</el-table-column>
					<el-table-column label="操作" class-name="small-padding fixed-width" width="130px" fixed="right" align="center">
						<template slot-scope="scope">
							<el-button size="mini" type="text" icon="el-icon-plus" @click="addComponents(scope.row)">添加</el-button>
							<el-button size="mini" type="text" icon="el-icon-delete" @click="deleteComponents(scope.$index, scope.row)">删除</el-button>
						</template>
					</el-table-column>
				</el-table>
			</div>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitFormcomponents">确 定</el-button>
				<el-button @click="editconponents = false">取 消</el-button>
			</div>
		</el-dialog>

		<el-dialog title="退修原因" :visible.sync="openreason" width="900px" append-to-body v-dialogDrag>
			<el-form ref="reasonform" :model="reasonform" label-width="120px">
				<el-form-item label="退修原因" prop="receptionTime">
					<el-input v-model="reasonform.retirementRepairReason" type="textarea" maxlength="100" show-word-limit rows="3"></el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button type="primary" @click="submitFormReason">确 定</el-button>
				<el-button @click="cancelReason">取 消</el-button>
			</div>
		</el-dialog>
	</div>
</template>

<script>
import { retirementRepair } from "@/api/repair/repair"
import { component1Id, componentList, redundancyEdit, editRecord, listFault, listFaultChild1, getFault, editFault, breakdownUp, submitProduction, productionApprove, editFaultMore, RecordList } from "@/api/fault/faultlist"
import RepairInfo from "@/views/components/RepairInfo"
import FileUpload from "@/components/FileUpload"
import CreateForm from "@/views/components/CreateForm"
import { mapGetters } from "vuex"
import { approvalRecord } from "@/api/productTechnology/productTechnologyVersions"
import ApproveTemplete from "@/views/components/ApproveTemplete"
import RecordsTemplete from "@/views/components/RecordsTemplete"
import { getUserList, getworkerList } from "@/api/selectList"
import { downloadWithName, downloadFile } from "@/utils/requestBlob"
import { getcolumn, allocatedList } from "@/api/selectList"
import searchStateMixin from "@/layout/mixin/searchStateMixin.js"
export default {
	name: "Faultlist",
	mixins: [searchStateMixin],
	dicts: ["default_approve", "fault_status", "maintain_cat"],
	components: { RepairInfo, FileUpload, CreateForm, ApproveTemplete, RecordsTemplete },
	computed: {
		...mapGetters(["sidebar"])
	},
	data() {
		return {
			allocatedListData: [],
			ApprovalStatusList: [
				{
					id: "0",
					name: "未提交"
				},
				{
					id: "1",
					name: "审批中"
				},
				{
					id: "2",
					name: "已通过"
				},
				{
					id: "3",
					name: "未通过"
				}
			],
			tableTreeRefreshTool: {}, // 用于存储 resolve 方法和展开状态
			tableKey: 0, // 控制表格重新渲染的 key
			repairIdRow: "",
			loadings: false,
			reasonId: "",
			reasonform: {},
			openreason: false,
			isMousedownTable: false, //是否按下表格
			currentEnterRow: null, //当前移入的行数据
			worksData: [],
			editRowComponent: {},
			detailscomponentsList: [],
			editconponents: false,
			compentRecords: [],
			componentOpen: false,
			editRowForm: {},
			detailsRecordsList: [],
			editRecords: false,
			usersData: [],
			FormRecords: {},
			partRecords: false,
			productRecords: [],
			eleTabTop: 0, //表格容器距浏览器顶部距离
			testval: undefined,
			// 遮罩层
			loading: true,
			// 选中数组
			ids: [],
			rows: [],
			// 非单个禁用
			single: true,
			// 非多个禁用
			multiple: true,
			// 显示搜索条件
			showSearch: true,
			// 总条数
			total: 0,
			// 设备保养计划表格数据
			FaultList: [],
			// 弹出层标题
			title: "",
			// 是否显示弹出层
			open: false,
			// 查询参数
			queryParams: {
				pageNum: 1,
				pageSize: 10,
				repairNumber: undefined,
				malfunctionStatus: undefined,
				productName: undefined,
				productModel: undefined,
				productNumber: undefined,
				malfunctionApprovalStatus: undefined
			},
			// 表单参数
			form: {},
			// 表单校验
			rules: {
				malfunctionVerifyTime: [{ required: true, message: "请选择故障日期" }],
				maintenanceCategoryId: [{ required: true, message: "请选择维修类别" }],
				malfunctionStatus: [{ required: true, message: "请选择核实状态" }]
			},
			deviceList: [],
			// 更新树刷新
			treeMap: new Map(),
			disabled: false,
			openDetail: false,
			uploadOpen: false,
			// 上传
			uploadForm: {},
			uploadRules: {
				processNumber: [{ required: true, message: "请输入工艺通知单编号" }]
			},
			uploadList: [],
			treetablekey: Math.random(),
			// 审批数据
			openApprove: false,
			approveRow: undefined,
			// 审批流程
			openRecords: false,
			approveRecord: [],
			// 列信息
			columns: [
				{ key: 0, label: `返修任务单`, visible: true },
				{ key: 1, label: `客户代表`, visible: true },
				{ key: 2, label: `用户`, visible: true },
				{ key: 3, label: `产品名称`, visible: true },
				{ key: 4, label: `产品型号`, visible: true },
				{ key: 5, label: `产品编号`, visible: true },
				{ key: 6, label: `产品数量`, visible: true },
				{ key: 7, label: `核实故障日期`, visible: true },
				{ key: 8, label: `维修类别`, visible: true },
				{ key: 9, label: `故障模式`, visible: true },
				{ key: 10, label: `故障核实情况`, visible: true },
				{ key: 11, label: `状态`, visible: true },
				{ key: 12, label: `工艺通知单编号`, visible: true },
				{ key: 13, label: `审批状态`, visible: true },
				{ key: 14, label: `核查单上传`, visible: true },
				{ key: 15, label: `退修状态`, visible: true },
				{ key: 16, label: `退修原因`, visible: true }
			],
			isActive: false
		}
	},

	deactivated() {},
	created() {
		this.workData()
		this.getUsers()
		this.getallocatedList()
		//获取表格容器距页面头部的距离

		// 页面刷新，重置查询
		if (window.performance && performance.navigation.type === performance.navigation.TYPE_RELOAD) {
			// 清除URL中的查询参数
			this.resetForm("queryForm")
			window.history.replaceState({}, document.title, window.location.pathname)
		}
	},
	mounted() {
		// 滚动条的获取
		this.handleScrollx()
		window.addEventListener("scroll", this.handleScrollx, true)
	},
	watch: {
		"$route.query": {
			handler(newQuery, oldQuery) {
				// this.localSearchParams = { ...this.queryParams, ...this.localSearchParams }
				if (newQuery.queryData && Object.keys(newQuery.queryData).length != 0) {
					this.queryParams = { ...this.queryParams, ...JSON.parse(newQuery.queryData) }
					//  this.localSearchParams = { ...this.defaultSearchParams, ...this.localSearchParams }
				}
				this.getSize()
			},
			immediate: true, // 立即执行一次
			deep: true // 深度监听
		}
	},
	activated() {},
	destroyed() {
		window.removeEventListener("scroll", this.handleScrollx, true)
	},
	methods: {
		// 列表附件
		handleAnnex(row) {
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					paths: "/fault/faultlist",
					TableId: row.id,
					typeId: 11,
					perm: "fault:faultlist:annex",
					show: true,
					repairNumber: row.repairNumber
					// queryParams: JSON.stringify(this.queryParams)
				}
			})
		},
		// 产品附件
		handleAnnex2(row) {
			let id = row.id.replace("c", "")
			this.$router.push({
				path: "/attachment/attachmentUpload",
				query: {
					TableId: id,
					paths: "/fault/faultlist",
					typeId: 12,
					perm: "fault:faultlist:annex2",
					show: true,
					productName: row.productName,
					productModel: row.productModel
					// queryParams: JSON.stringify(this.queryParams)
				}
			})
		},
		getallocatedList() {
			allocatedList().then(res => {
				this.allocatedListData = res.rows
			})
		},
		getSize() {
			getcolumn({ pageName: "Pagination17" }).then(response => {
				this.queryParams.pageSize = response.data.length ? (response.data[0].limit ? response.data[0].limit : 10) : 10
				this.getList()
			})
		},
		detailsDownload(row) {
			downloadWithName(`/erp/repairProduct/component1/${row.id}`, {}).finally(() => {})
		},
		modality(row) {
			console.log(row)
		},
		submitFormReason() {
			retirementRepair({
				id: this.reasonId,
				retirementRepairReason: this.reasonform.retirementRepairReason,
				retirementRepairlStatus: 1
			}).then(res => {
				this.$modal.msgSuccess("修改成功")
				this.openreason = false
				localStorage.setItem("todoMessage", "fault1")
				this.refreshLoadTree(this.repairIdRow) // 刷新子级数据
				this.getList()
				this.rows = []
				this.ids = []
				this.$refs.table.clearSelection()
				this.$forceUpdate()
			})
		},
		resetReason() {
			this.reasonform = {
				retirementRepairReason: null
			}
		},
		cancelReason() {
			this.resetReason()
			this.openreason = false
		},
		handlebacks(row) {
			this.repairIdRow = row.repairId
			this.resetReason()
			this.openreason = true
			this.reasonId = row.id.replace("c", "")
		},
		handleRowClick(row, column, event) {
			console.log("行点击事件触发", row, column, event)
		},
		submitFormcomponents() {
			this.editRowComponent.tcomponentInspectionRecordDetailList = this.detailscomponentsList
			redundancyEdit(this.editRowComponent).then(res => {
				this.$modal.msgSuccess("修改成功")
				localStorage.setItem("todoMessage", "fault2")
				this.editconponents = false
			})
		},
		addComponents(row, index) {
			let data = this.detailscomponentsList
			if (data[data.length - 1].processNumber && data[data.length - 1].processName && data[data.length - 1].conclusion && data[data.length - 1].workerId && data[data.length - 1].recipientId && data[data.length - 1].workerTime && data[data.length - 1].recipientTime) {
				data.push({
					remark: undefined,
					processNumber: undefined,
					processName: undefined,
					conclusion: undefined,
					workerId: undefined,
					recipientId: undefined,
					workerTime: undefined,
					recipientTime: undefined
				})
			} else {
				this.$modal.msgError("请将数据填写完整")
			}
		},
		deleteComponents(index, row) {
			this.detailscomponentsList.splice(index, 1)
		},
		selectComponentusers(e, row) {
			this.worksData.forEach(item => {
				if (e == item.userId) {
					row.workerName = item.nickName
				}
			})
		},
		selectComponentrecipient(e, row) {
			this.usersData.forEach(item => {
				if (e == item.userId) {
					row.recipientName = item.nickName
				}
			})
		},
		selectusers(e, row) {
			this.allocatedListData.forEach(item => {
				if (e == item.userId) {
					row.recipientName = item.nickName
				}
			})
		},
		detailsComponents(row) {
			this.editRowComponent = row
			this.detailscomponentsList = row.tcomponentRedundancies.length == 0 ? [{}] : row.tcomponentRedundancies
			this.editconponents = true
		},
		detailsRecords(row) {
			this.editRowForm = row
			this.detailsRecordsList = row.tcomponentInspectionRecordDetailList.length == 0 ? [{}] : row.tcomponentInspectionRecordDetailList
			this.editRecords = true
		},
		submitFormRecords() {
			this.editRowForm.tcomponentInspectionRecordDetailList = this.detailsRecordsList
			editRecord(this.editRowForm).then(res => {
				this.$modal.msgSuccess("修改成功")
				localStorage.setItem("todoMessage", "fault3")
				this.editRecords = false
			})
		},
		addRecords(row, index) {
			let data = this.detailsRecordsList
			if (data[data.length - 1].programTests && data[data.length - 1].conclusion && data[data.length - 1].recipientId) {
				data.push({
					programTests: undefined,
					conclusion: undefined,
					recipientId: undefined,
					remark: undefined
				})
			} else {
				this.$modal.msgError("请将数据填写完整")
			}
		},
		deleteRecords(index, row) {
			this.detailsRecordsList.splice(index, 1)
		},
		getUsers() {
			getUserList({
				deptId: 116
			}).then(res => {
				this.usersData = res.rows
			})
		},
		workData() {
			getworkerList().then(res => {
				this.worksData = res.rows
			})
		},
		handleControl(row) {
			componentList({
				repairId: row.id
			}).then(res => {
				res.rows.forEach(item => {
					if (item.tcomponentRedundancies.length == 0) {
						item.tcomponentRedundancies = [{}]
					}
				})
				this.compentRecords = res.rows
				this.componentOpen = true
			})
		},
		handleIng(row) {
			RecordList({
				repairId: row.id
			}).then(res => {
				res.rows.forEach(item => {
					if (!item.tcomponentInspectionRecordDetailList) {
						item.tcomponentInspectionRecordDetailList = [{}]
					}
				})
				this.productRecords = res.rows
				this.partRecords = true
			})
		},
		//获取表格容器距页面头部的距离
		handleScrollx() {
			this.eleTabTop = this.$refs.eleTab.getBoundingClientRect().top
		},
		/** 查询设备保养计划列表 */
		getList() {
			this.loading = true
			listFault(this.queryParams).then(response => {
				this.FaultList = response.rows
				this.FaultList.forEach((item, index) => {
					item.hasChildren = true
					item.sort = index + 1
				})
				this.total = response.total
				this.loading = false
			})
		},
		refreshLoadTree(parentId) {
			const { tree, treeNode, resolve } = this.treeMap.get(parentId)
			tree.children = [] // 清空旧数据
			this.loadListDes(tree, treeNode, resolve) // 重新加载子级数据
			this.$refs.table.clearSelection() // 刷新树时清空选中状态
		},
		updateParentStatus(parentId) {
			const parentRow = this.FaultList.find(item => item.id === parentId)
			console.log(parentRow)
			if (!parentRow) return

			// 获取所有子级数据
			const children = parentRow.children || []
			const allApproved = children.every(child => child.malfunctionApprovalStatus === "2") // 假设审批状态为 '2' 表示已通过
			const anyRejected = children.some(child => child.malfunctionApprovalStatus === "3") // 假设审批状态为 '3' 表示未通过

			if (allApproved) {
				parentRow.malfunctionApprovalStatus = "2" // 父级状态更新为已通过
			} else if (anyRejected) {
				parentRow.malfunctionApprovalStatus = "3" // 父级状态更新为未通过
			} else {
				parentRow.malfunctionApprovalStatus = "1" // 父级状态更新为审批中
			}

			this.$forceUpdate() // 强制更新视图
		},
		// 关闭所有展开的行
		closeAllExpansions() {
			// this.FaultList.forEach(row => {
			// 	this.$refs.table.toggleRowExpansion(row, false)
			// })
			this.ids = []
			this.rows = []
			this.$refs.table.clearSelection()
			this.getList()
		},
		// 展开/收起时触发
		handleExpandChange(row, expanded) {
			const curr = this.tableTreeRefreshTool[row.id]
			if (!curr) return
			curr.expandCount++
			if (expanded && curr.expandCount > 1 && !curr.prevStatus) {
				listFaultChild1({
					id: row.id,
					productName: this.queryParams.productName,
					productModel: this.queryParams.productModel,
					productNumber: this.queryParams.productNumber,
					repairNumber: this.queryParams.repairNumber,
					malfunctionStatus: this.queryParams.malfunctionStatus
				}).then(res => {
					res.rows.forEach((item, index) => {
						// 父子id会冲突
						item.id = "c" + item.id
						item.sort = index + 1
					})
					curr.resolve(res.rows)
				})
			}
			curr.prevStatus = expanded
			if (!expanded) {
				this.$refs.table.clearSelection() // 收起时清空选中状态
			}
		},
		// 获取列表详情
		async loadListDes(tree, treeNode, resolve) {
			if (!this.treeMap.has(tree.id)) {
				this.treeMap.set(tree.id, { tree: tree, treeNode, resolve })
			}
			this.tableTreeRefreshTool[tree.id] = {
				resolve,
				expandCount: 0, // 展开次数
				prevStatus: false // 上一次的展开状态
			}
			let data = {
				id: tree.id,
				productName: this.queryParams.productName,
				productModel: this.queryParams.productModel,
				productNumber: this.queryParams.productNumber,
				repairNumber: this.queryParams.repairNumber,
				malfunctionStatus: this.queryParams.malfunctionStatus
			}
			let ret = await listFaultChild1(data)

			if (!ret.rows || ret.rows.length == 0) {
				tree.children = [] // 如果返回空数组，手动设置为空数组
				this.getList()
				this.$forceUpdate()
			} else {
				ret.rows.forEach((item, index) => {
					// 父子id会冲突
					item.id = "c" + item.id
					item.sort = index + 1
				})
				tree.children = ret.rows
				this.$set(tree, "children", ret.rows) // 确保响应式更新
			}

			resolve(ret.rows)
			this.$forceUpdate()
		},
		// 取消按钮
		cancel() {
			this.open = false
			this.$refs.table.clearSelection()
			this.reset()
		},
		// 表单重置
		reset() {
			this.form = {
				repairId: undefined,
				repairNumber: undefined,
				productName: undefined,
				productModel: undefined,
				processNumber: undefined,
				productNumber: undefined,
				receiptTime: undefined,
				malfunctionVerifyTime: undefined,
				maintenanceCategoryId: undefined,
				maintenanceCategoryName: undefined,
				failureMode: undefined,
				malfunctionStatus: undefined,
				failureRemark: undefined
			}
			this.resetForm("form")
		},
		/** 搜索按钮操作 */
		handleQuery() {
			this.queryParams.pageNum = 1
			// 保存搜索条件
			this.saveSearchState()
			// this.closeAllExpansions()
			//
			this.getList()
			// this.treetablekey = Math.random()
		},
		/** 重置按钮操作 */
		resetQuery() {
			this.resetForm("queryForm")
			this.queryParams.malfunctionStatus = undefined
			this.queryParams.malfunctionApprovalStatus = undefined
			this.clearSearchCache()
			this.handleQuery()
		},
		// 多选框选中数据
		handleSelectionChange(selection) {
			this.ids = selection.map(item => item.id)
			this.rows = JSON.parse(JSON.stringify(selection))
			this.single = selection.length !== 1
			this.multiple = !selection.length
		},
		// 表格按下
		mousedownTable(event) {
			const target = event.target
			// 判断target的class属性确定是否点击在复选框上
			if (target.classList.contains("el-checkbox__inner")) {
				this.currentEnterRow && this.$refs.table.toggleRowSelection(this.currentEnterRow)
				this.isMousedownTable = true
			}
		},
		// 单击表格行
		row_click(row, column, event) {
			// this.currentEnterRow || this.$refs.table.toggleRowSelection(row)
			if (column && column.label == "操作") {
				return
			} else {
				this.$refs.table.toggleRowSelection(row)
			}
		},
		changeTableData() {
			this.$nextTick(() => {
				this.$refs.table.doLayout()
			})
		},

		// 进入单元格
		cell_mouse_enter(row, column, cell, event) {
			this.isMousedownTable && this.$refs.table.toggleRowSelection(row)
			this.currentEnterRow = row
		},
		// 离开单元格
		cell_mouse_leave(row, column, cell, event) {
			this.currentEnterRow = null
		},
		// 鼠标弹起或者离开表格
		mouseupTable(d) {
			this.isMousedownTable = false
		},
		/** 故障核实 */
		handleEdit(row) {
			this.disabled = false
			this.reset()
			const id = row.id.replace("c", "")
			getFault(id).then(response => {
				this.form = response.data
				if (this.form.malfunctionStatus == "2") {
					this.form.malfunctionStatus = "3"
				}
				this.open = true
				this.title = "故障核实"
				this.$nextTick(() => {
					this.$refs.form.clearValidate()
				})
				this.rows = []
				this.ids = []
				this.$refs.table.clearSelection()
			})
		},
		// 批量故障核实
		handleEditMore() {
			if (this.ids.length == 0) {
				this.$modal.msg("请选择产品")
				return false
			} else {
				// 判断是否选中了父级返修任务
				let checkp = this.rows.find(item => {
					return Number(item.id) > 0
				})
				if (checkp) {
					this.$modal.msg("只能选择子类产品")
					return false
				}
			}
			this.disabled = false
			let ids = []
			this.ids.forEach(item => {
				ids.push(item.replace("c", ""))
			})
			ids = [...new Set(ids)]
			let flag = this.rows.every(item => item.malfunctionApprovalStatus == "0" || item.malfunctionApprovalStatus == "3")
			this.form = {
				failureMode: undefined,
				failureRemark: undefined,
				id: 0,
				ids: ids,
				maintenanceCategoryId: undefined,
				maintenanceCategoryName: undefined,
				malfunctionStatus: undefined,
				malfunctionVerifyTime: undefined
			}
			this.resetForm("form")
			this.open = true
			this.title = "故障核实"
			this.form.malfunctionStatus = "3"
			this.$nextTick(() => {
				this.$refs.form.clearValidate()
			})
			// 刷新树
			// this.treeMap.forEach((item, idx) => {
			// 	this.loadListDes({ id: idx }, item.treeNode, item.resolve)
			// })
			this.rows = []
			this.ids = []
			this.$refs.table.clearSelection()
		},
		handleSubmits() {
			if (this.ids.length == 0) {
				this.$modal.msg("请选择产品")
				return false
			} else {
				// 判断是否选中了父级返修任务
				let checkp = this.rows.find(item => {
					return Number(item.id) > 0
				})
				if (checkp) {
					this.$modal.msg("只能选择子类产品")
					return false
				}
			}
			let ids = []
			this.ids.forEach(item => {
				ids.push(item.replace("c", ""))
			})
			ids = [...new Set(ids)]
			let _that = this
			this.$modal
				.confirm("是否确认提交数据项？")
				.then(() => {
					_that.loadings = this.$loading({
						lock: true,
						text: "Loading",
						spinner: "el-icon-loading",
						background: "rgba(0, 0, 0, 0.7)"
					})
					submitProduction({
						workIds: ids,
						workflowType: "11"
					}).then(res => {
						if (res.code == 200) {
							this.$modal.msgSuccess("操作成功")
							// 刷新树
							this.treeMap.forEach((item, idx) => {
								this.loadListDes({ id: idx }, item.treeNode, item.resolve)
							})
							this.rows = []
							this.ids = []
							this.$refs.table.clearSelection()
							_that.loadings.close()
						} else {
							_that.loadings.close()
						}
					})
				})
				.catch(() => {
					_that.loadings.close()
				})
				.finally(() => {
					_that.loadings.close()
				})
		},
		// 提交，只有子级
		handleSubmit(row) {
			const id = row.id.replace("c", "")
			this.$modal
				.confirm("是否确认提交数据项？")
				.then(function () {
					let data = {
						workId: id,
						workflowType: "11",
						// 1是提交，3是重复提交
						submitStatus: row.malfunctionApprovalStatus == "0" ? "1" : "2"
					}
					return submitProduction(data)
				})
				.then(() => {
					this.$modal.msgSuccess("操作成功")
					// 刷新树
					this.treeMap.forEach((item, idx) => {
						this.loadListDes({ id: idx }, item.treeNode, item.resolve)
					})
					this.rows = []
					this.ids = []
					this.$refs.table.clearSelection()
				})
				.catch(() => {})
		},
		// 详情
		handleDetailChild(row) {
			this.disabled = true
			this.reset()
			const id = row.id.replace("c", "")
			getFault(id).then(response => {
				this.form = response.data
				this.open = true
				this.title = "故障核实"
				// this.form.malfunctionStatus = "2"
				this.$nextTick(() => {
					this.$refs.form.clearValidate()
				})
			})
		},
		// 更改维修类别
		changeCat() {
			let cur = this.dict.type.maintain_cat.find(ele => {
				return ele.value == this.form.maintenanceCategoryId
			})
			this.form.maintenanceCategoryName = cur.label
		},
		updateParentStatus1(parentId) {
			const parentRow = this.FaultList.find(item => item.id === parentId)
			if (!parentRow) return

			// 获取所有子级数据
			const children = parentRow.children || []
			const allApproved = children.every(child => child.malfunctionStatus != "2") // 假设审批状态为 '2' 表示已通过
			// const anyRejected = children.some(child => child.malfunctionApprovalStatus === "3") // 假设审批状态为 '3' 表示未通过

			if (allApproved) {
				parentRow.repairMalfunctionStatus = "2" // 父级状态更新为已通过
			} else if (anyRejected) {
				parentRow.malfunctionApprovalStatus = "3" // 父级状态更新为未通过
			} else {
				parentRow.malfunctionApprovalStatus = "1" // 父级状态更新为审批中
			}
			this.$forceUpdate() // 强制更新视图
		},
		/** 提交按钮 */
		submitForm() {
			this.$refs["form"].validate(valid => {
				if (valid) {
					const loading = this.$loading({
						lock: true,
						text: "Loading",
						spinner: "el-icon-loading",
						background: "rgba(0, 0, 0, 0.7)"
					})
					if (this.form.id == 0) {
						// 批量
						editFaultMore(this.form)
							.then(response => {
								this.$modal.msgSuccess("操作成功")
								this.$refs.table.clearSelection()
								this.open = false
								this.getList()
								localStorage.setItem("todoMessage", "fault5")
								this.rows = []
								this.ids = []
								this.$forceUpdate()
								this.treetablekey = Math.random()
							})
							.catch(() => {
								loading.close()
							})
							.finally(() => {
								loading.close()
							})
					} else {
						// 单个
						editFault(this.form)
							.then(response => {
								this.$modal.msgSuccess("操作成功")
								this.open = false
								this.refreshLoadTree(this.form.repairId) // 刷新子级数据
								this.updateParentStatus1(this.form.repairId)
								this.getList()
								this.rows = []
								this.ids = []
								localStorage.setItem("todoMessage", "fault6")
								loading.close()
								this.$forceUpdate()
							})
							.catch(() => {
								loading.close()
							})
							.finally(() => {
								loading.close()
							})
					}
				}
			})
		},
		// 返修单详情详情
		handleDetail(row) {
			this.openDetail = true
			this.$nextTick(() => {
				this.$refs.repairdetail.resetFormData(row.id)
			})
		},
		handleUpload() {
			let formids = []
			// 多条记录
			if (this.ids.length == 0) {
				this.$modal.msg("请选择产品")
				return false
			} else {
				// 判断是否选中了父级返修任务
				let checkp = this.rows.find(item => {
					return Number(item.id) > 0
				})
				if (checkp) {
					this.$modal.msg("只能选择子类产品")
					return false
				}
				// 判断选中的产品列表是否是同一个产品型号
				let modal = undefined
				let check = this.rows.every(e => {
					let id = e.id.replace("c", "")
					formids.push(id)
					if (!e.productModel) {
						return false
					} else {
						if (!modal) {
							modal = e.productModel
							return true
						} else {
							return modal == e.productModel
						}
					}
				})
				if (!check) {
					this.$modal.msg("请选择同一产品型号的生产计划")
					return false
				}
			}
			this.uploadReset(formids)
			this.uploadOpen = true
		},
		// 表单上传工艺通知单重置
		uploadReset(formids) {
			this.uploadForm = {
				productIds: formids,
				fileList: [],
				processNumber: undefined
			}
			this.uploadList = []
			this.resetForm("uploadform")
		},
		submitFormUpload() {
			this.$refs["uploadform"].validate(valid => {
				if (valid) {
					if (this.uploadList.length == 0) {
						this.$modal.msgError("请先上传文件")
						return false
					}
					this.uploadForm.fileList = this.uploadList
					breakdownUp(this.uploadForm).then(response => {
						this.$modal.msgSuccess("操作成功")
						this.uploadOpen = false
						this.getList()
						this.rows = []
						this.ids = []
						// 清空已选
						this.$refs.table.clearSelection()
						this.$forceUpdate()
					})
				}
			})
		},
		cancelUpload() {
			this.$refs.table.clearSelection()
			this.uploadOpen = false
		},

		// 审批
		handleApprove(row) {
			if (row.id) {
				this.repairIdRow = row.repairId
				this.approveRow = row
				this.openApprove = true
			} else {
				this.approveRow = {}
				let checkp = this.rows.find(item => {
					return Number(item.id) > 0
				})
				if (checkp) {
					this.$modal.msg("只能选择子类产品")
					return false
				}
				this.openApprove = true
			}
		},
		// 审批取消
		async cancelApprove(ret) {
			if (!ret.flag) {
				this.openApprove = false
				return false
			}
			let ids = []
			if (this.ids.length != 0) {
				this.ids.forEach(item => {
					ids.push(item.replace("c", ""))
				})
				ids = [...new Set(ids)]
			}

			let data = {
				approvalStatus: ret.approvalStatus,
				causeRejection: ret.causeRejection,
				workflowType: "11"
			}
			this.approveRow.id ? (data.id = this.approveRow.id.replace("c", "")) : (data.ids = ids)
			let flag = this.approveRow.id ? true : false
			const loading = this.$loading({
				lock: true,
				text: "Loading",
				spinner: "el-icon-loading",
				background: "rgba(0, 0, 0, 0.7)"
			})
			productionApprove(data)
				.then(res => {
					if (res.code == 200) {
						this.$modal.msgSuccess("操作成功")
						loading.close()
						if (flag) {
							this.refreshLoadTree(this.repairIdRow) // 刷新子级数据.
							this.updateParentStatus2(this.repairIdRow)
							this.getList()
							this.$forceUpdate()
						} else {
							this.getList()
							this.treetablekey = Math.random()
							this.$forceUpdate()
						}
						this.rows = []
						this.ids = []
						this.$refs.table.clearSelection()
						localStorage.setItem("todoMessage", "fault50")
					} else {
						loading.close()
					}
				})
				.catch(() => {
					loading.close()
				})

			this.openApprove = false
		},
		updateParentStatus2(parentId) {
			const parentRow = this.FaultList.find(item => item.id === parentId)
			if (!parentRow) return

			// 获取所有子级数据
			const children = parentRow.children || []
			const allApproved = children.every(child => child.malfunctionApprovalStatus == "2") // 假设审批状态为 '2' 表示已通过

			if (allApproved) {
				parentRow.malfunctionApprovalStatus = "2" // 父级状态更新为已通过
			}
			this.$forceUpdate() // 强制更新视图
		},
		// 获取审批详情
		showApproveList(row) {
			if (row.malfunctionApprovalStatus == "0") {
				return false
			}
			this.openRecords = true
			let id = row.id.replace("c", "")
			approvalRecord({
				id: id,
				workflowType: "11"
			}).then(res => {
				this.openRecords = true
				this.approveRecord = res.data
			})
		},

		truncateAtLastDecimal(str) {
			return str.replace(/(\.\d+)?$/, "")
		},
		// 上传
		getFiles(files) {
			this.uploadList = files
			var fileNameWithoutExtension = files[0].fileName.split(".").slice(0, -1).join(".")
			this.uploadForm.processNumber = fileNameWithoutExtension
		}
	}
}
</script>

<style lang="scss" scoped>
.selects {
	background-color: red !important;
	color: red;
}

// 列表计划名称左对齐，标题居中
.form-title {
	width: 100%;
	height: 3rem;
	padding-left: 1rem;

	.title-msg {
		padding-bottom: 0.8rem;
		border-bottom: 2px solid rgb(42, 130, 228);
	}
}

::v-deep .el-table__fixed-header-wrapper .fixed-width {
	width: 260px !important;
}
</style>
